package pre.bookcloud.java21.qoder.todaysign01;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Random;

/**
 * Student Sign-in Statistical Chart
 * 学生签到统计图表
 */
public class SignStatisticalChart extends JPanel {
    
    private ChartPanel chartPanel;
    private JFreeChart chart;
    
    public SignStatisticalChart() {
        initializeChart();
        setupLayout();
    }
    
    /**
     * Initialize the chart
     * 初始化图表
     */
    private void initializeChart() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);
        
        // Create the chart
        chart = createCombinedChart();
        chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(900, 500));
        chartPanel.setBackground(Color.WHITE);
        
        // Customize chart panel
        chartPanel.setDisplayToolTips(true);
        chartPanel.setMouseZoomable(true);
        chartPanel.setMouseWheelEnabled(true);
    }
    
    /**
     * Setup the layout
     * 设置布局
     */
    private void setupLayout() {
        add(chartPanel, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    }
    
    /**
     * Create combined bar and line chart
     * 创建组合柱状图和折线图
     */
    private JFreeChart createCombinedChart() {
        // Create datasets
        CategoryDataset barDataset = createBarDataset();
        CategoryDataset lineDataset = createLineDataset();
        
        // Create the chart with bar renderer
        JFreeChart chart = ChartFactory.createBarChart(
            "学生签到统计",  // Chart title
            "学生",          // X-axis label
            "次数",          // Y-axis label
            barDataset,      // Dataset
            PlotOrientation.VERTICAL,
            true,           // Include legend
            true,           // Tooltips
            false           // URLs
        );
        
        // Get the plot
        CategoryPlot plot = chart.getCategoryPlot();
        
        // Customize the plot
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        
        // Customize bar renderer
        BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
        barRenderer.setSeriesPaint(0, new Color(135, 206, 250)); // Light blue for 签到次数
        barRenderer.setSeriesPaint(1, new Color(255, 99, 71));   // Tomato red for 未签到次数
        barRenderer.setItemMargin(0.1);
        
        // Add line renderer for the percentage line
        LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
        lineRenderer.setSeriesPaint(0, new Color(255, 165, 0));  // Orange for 签到率
        lineRenderer.setSeriesStroke(0, new BasicStroke(2.0f));
        lineRenderer.setSeriesShapesVisible(0, true);
        lineRenderer.setSeriesShape(0, new java.awt.geom.Ellipse2D.Double(-3, -3, 6, 6));
        
        // Create second Y-axis for percentage
        NumberAxis percentageAxis = new NumberAxis("签到率(%)");
        percentageAxis.setRange(0, 100);
        percentageAxis.setLabelPaint(new Color(255, 165, 0));
        percentageAxis.setTickLabelPaint(new Color(255, 165, 0));
        
        // Set the second dataset and renderer
        plot.setDataset(1, lineDataset);
        plot.setRenderer(1, lineRenderer);
        plot.setRangeAxis(1, percentageAxis);
        plot.mapDatasetToRangeAxis(1, 1);
        
        // Customize X-axis
        CategoryAxis xAxis = plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(org.jfree.chart.axis.CategoryLabelPositions.UP_45);
        xAxis.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        xAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 10));
        
        // Customize Y-axes
        NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(0);
        yAxis.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        yAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 10));
        yAxis.setLowerBound(0); // Set minimum value to 0 to remove negative values
        
        percentageAxis.setLabelFont(new Font("微软雅黑", Font.PLAIN, 12));
        percentageAxis.setTickLabelFont(new Font("微软雅黑", Font.PLAIN, 10));
        percentageAxis.setLowerBound(0); // Ensure percentage axis starts from 0
        
        // Customize title
        chart.getTitle().setFont(new Font("微软雅黑", Font.BOLD, 16));
        
        // Customize legend
        chart.getLegend().setItemFont(new Font("微软雅黑", Font.PLAIN, 12));
        
        return chart;
    }
    
    /**
     * Create bar chart dataset for sign-in counts
     * 创建签到次数的柱状图数据集
     */
    private CategoryDataset createBarDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        
        // Get student data and generate historical statistics
        List<Student> students = DataUtil.getTodaySignData();
        Random random = new Random(42); // Fixed seed for consistent data
        
        for (Student student : students) {
            // Generate mock historical data for demonstration
            int totalDays = 30; // Assume 30 days of records
            int signedDays = random.nextInt(25) + 5; // 5-29 signed days
            int unsignedDays = totalDays - signedDays;
            
            dataset.addValue(signedDays, "签到次数", student.getName());
            dataset.addValue(unsignedDays, "未签到次数", student.getName());
        }
        
        return dataset;
    }
    
    /**
     * Create line chart dataset for sign-in rate
     * 创建签到率的折线图数据集
     */
    private CategoryDataset createLineDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        
        // Get student data and calculate sign-in rates
        List<Student> students = DataUtil.getTodaySignData();
        Random random = new Random(42); // Fixed seed for consistent data
        
        for (Student student : students) {
            // Generate mock historical data for demonstration
            int totalDays = 30;
            int signedDays = random.nextInt(25) + 5; // 5-29 signed days
            double signInRate = (double) signedDays / totalDays * 100;
            
            dataset.addValue(signInRate, "签到率", student.getName());
        }
        
        return dataset;
    }
    
    /**
     * Refresh chart data
     * 刷新图表数据
     */
    public void refreshChart() {
        CategoryDataset barDataset = createBarDataset();
        CategoryDataset lineDataset = createLineDataset();
        
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setDataset(0, barDataset);
        plot.setDataset(1, lineDataset);
    }
    
    /**
     * Get chart panel for embedding in other components
     * 获取图表面板用于嵌入其他组件
     */
    public ChartPanel getChartPanel() {
        return chartPanel;
    }
}